using DapperExtensionsNew.Data;
using DapperExtensionsNew.Utils;
using System.Text;

namespace DapperExtensionsNew.Configuration.AnalyzerOptions
{
	internal class MsSqlDatabaseOptions : SqlDatabaseOptions
	{
		public MsSqlDatabaseOptions()
		{
			base.StartDelimiter = "[";
			base.EndDelimiter = "]";
			base.Encapsulation = "[{0}]";
			base.IdentitySql = "SELECT CAST(SCOPE_IDENTITY()  AS BIGINT) AS [id]";
			base.FromSql = " from {0} WITH (NOLOCK) ";
			base.PagedListSql = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY {OrderBy}) AS PagedNumber, {SelectColumns} FROM {TableName} WITH (NOLOCK) {WhereClause} {IsDeleted}) AS u WHERE PagedNUMBER BETWEEN (({PageNumber}-1) * {RowsPerPage} + 1) AND ({PageNumber} * {RowsPerPage})";
			base.PagedListCountSql = "SELECT COUNT(1) FROM {TableName}  WITH (NOLOCK) {WhereClause} {IsDeleted}";
		}

		public override string GetOperationPatten(SqlOperation operation)
		{
			switch (operation)
			{
			case SqlOperation.Insert:
				return "INSERT INTO [{TableName}] ({Columns}) VALUES ({Values});  SELECT CAST(SCOPE_IDENTITY()  AS BIGINT) AS [id] ";
			case SqlOperation.Update:
				return "UPDATE [{TableName}] SET {SetColumns} {WhereClause}";
			case SqlOperation.Delete:
				return "DELETE FROM [{TableName}] {WhereClause}";
			default:
				return null;
			}
		}

		public override string GetSelectSql(string columns, string tableName)
		{
			StringBuilder stringBuilder = StringBuilderCache.Acquire();
			stringBuilder.Append("SELECT ");
			stringBuilder.Append(columns);
			stringBuilder.Append(" FROM [");
			stringBuilder.Append(tableName);
			stringBuilder.Append("] with(nolock)");
			return StringBuilderCache.GetStringAndRelease(stringBuilder);
		}

		public override string GetPageSql(int skip, int take)
		{
			return $" offset {skip} rows fetch next {take} rows only";
		}
	}
}
